<template>
  <div class="app-container">
    <div class="page-header">
      <div class="header-left">
        <el-button icon="el-icon-back" @click="goBack">返回</el-button>
        <h2 class="page-title">{{ userInfo.username }} 的游戏统计</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleExport">导出数据</el-button>
      </div>
    </div>

    <div class="statistics-container">
      <!-- 游戏时长统计卡片 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-card-content">
              <div class="stat-icon">
                <i class="el-icon-time"></i>
              </div>
              <div class="stat-info">
                <div class="stat-title">总游戏时长</div>
                <div class="stat-value">{{ formatTotalTime(userInfo.totalPlayTime) }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-card-content">
              <div class="stat-icon blue">
                <i class="el-icon-collection"></i>
              </div>
              <div class="stat-info">
                <div class="stat-title">已玩游戏数</div>
                <div class="stat-value">{{ userInfo.totalGames }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-card-content">
              <div class="stat-icon green">
                <i class="el-icon-trophy"></i>
              </div>
              <div class="stat-info">
                <div class="stat-title">获得成就</div>
                <div class="stat-value">{{ userInfo.achievementCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-card-content">
              <div class="stat-icon purple">
                <i class="el-icon-star-on"></i>
              </div>
              <div class="stat-info">
                <div class="stat-title">平均游戏评分</div>
                <div class="stat-value">{{ formattedRating }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>游戏类型分布</span>
                <el-tooltip content="用户玩过的不同类型游戏的分布情况" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </div>
            </template>
            <div ref="typeChartRef" class="chart-placeholder">
              <span v-if="loading">饼图：展示用户游戏类型偏好占比</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>每日游戏时长</span>
                <el-tooltip content="用户近30天的每日游戏时长趋势" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </div>
            </template>
            <div ref="timeChartRef" class="chart-placeholder">
              <span v-if="loading">折线图：展示用户近30天的游戏时长变化</span>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>游戏完成度对比</span>
                <el-tooltip content="用户不同游戏的完成进度比较" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </div>
            </template>
            <div ref="progressChartRef" class="chart-placeholder">
              <span v-if="loading">条形图：展示用户各游戏完成进度</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>游戏时间分布</span>
                <el-tooltip content="用户在一天中的不同时段的游戏时长分布" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </div>
            </template>
            <div ref="hourlyChartRef" class="chart-placeholder">
              <span v-if="loading">雷达图：展示一天中不同时段的游戏时间分布</span>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细游戏记录 -->
      <el-card shadow="hover" class="detail-card">
        <template #header>
          <div class="detail-header">
            <span>详细游戏记录</span>
            <div class="header-actions">
              <el-select v-model="timeRange" placeholder="时间范围" size="small">
                <el-option label="近7天" value="7" />
                <el-option label="近30天" value="30" />
                <el-option label="近3个月" value="90" />
                <el-option label="全部时间" value="all" />
              </el-select>
              <el-select v-model="sortOption" placeholder="排序方式" size="small">
                <el-option label="按游戏时长" value="playTime" />
                <el-option label="按最近游玩" value="lastPlayed" />
                <el-option label="按游戏名称" value="name" />
              </el-select>
            </div>
          </div>
        </template>

        <el-table v-loading="loading" :data="gameRecords" stripe style="width: 100%">
          <el-table-column prop="name" label="游戏名称" min-width="150" />
          <el-table-column label="游戏类型" width="120">
            <template #default="scope">
              <el-tag :type="getGameTypeTagType(scope.row.gameType)">
                {{ getGameTypeName(scope.row.gameType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="playTime" label="游戏时长" width="120">
            <template #default="scope">
              {{ formatTime(scope.row.playTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="startDate" label="首次游玩" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.startDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="lastPlayed" label="最近游玩" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.lastPlayed) }}
            </template>
          </el-table-column>
          <el-table-column label="游戏进度" min-width="200">
            <template #default="scope">
              <el-progress
                :percentage="scope.row.progress"
                :color="getProgressColor(scope.row.progress)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="rating" label="评分" width="100">
            <template #default="scope">
              <el-rate v-model="scope.row.rating" disabled text-color="#ff9900" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="text" @click="handleGameDetail(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 成就解锁时间轴 -->
      <el-card shadow="hover" class="timeline-card">
        <template #header>
          <div class="timeline-header">
            <span>成就解锁时间线</span>
          </div>
        </template>

        <el-timeline>
          <el-timeline-item
            v-for="(achievement, index) in userAchievements"
            :key="index"
            :timestamp="formatDate(achievement.unlockedDate)"
            :type="
              index % 4 === 0
                ? 'primary'
                : index % 4 === 1
                  ? 'success'
                  : index % 4 === 2
                    ? 'warning'
                    : 'danger'
            "
            :color="achievement.unlocked ? '' : '#909399'"
          >
            <el-card class="achievement-card">
              <div class="achievement-content">
                <div class="achievement-icon">
                  <i :class="achievement.icon"></i>
                </div>
                <div class="achievement-info">
                  <h4>{{ achievement.name }}</h4>
                  <p>{{ achievement.description }}</p>
                  <div class="achievement-game">
                    在
                    <strong>{{ achievement.game }}</strong>
                    中获得
                  </div>
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import UserGameAPI, {
  type GameUserInfo,
  type GameAchievement,
  type GameTypeDistribution,
} from "@/api/game/userinfo";

// 扩展GameAchievement类型
interface EnhancedGameAchievement extends GameAchievement {
  game?: string;
}

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const error = ref<any>(null);

// 图表实例
const timeChartRef = ref<HTMLElement | null>(null);
const typeChartRef = ref<HTMLElement | null>(null);
const hourlyChartRef = ref<HTMLElement | null>(null);
const progressChartRef = ref<HTMLElement | null>(null);

let timeChart: echarts.ECharts | null = null;
let typeChart: echarts.ECharts | null = null;
let hourlyChart: echarts.ECharts | null = null;
let progressChart: echarts.ECharts | null = null;

// 用户ID
const userId = computed(() => {
  // 尝试从路由params获取ID
  const idFromParams = route.params.id ? Number(route.params.id) : undefined;
  // 兼容从query获取ID的方式，向下兼容
  const idFromQuery = route.query.id ? Number(route.query.id) : undefined;

  // 优先使用params中的ID，如果没有则使用query中的ID
  const id = idFromParams || idFromQuery;

  console.log("统计页面获取到路由参数 - params ID:", idFromParams, "query ID:", idFromQuery);
  return id;
});

// 用户信息
const userInfo = reactive<GameUserInfo>({
  id: 0,
  username: "",
  avatar: "",
  level: 0,
  totalGames: 0,
  totalPlayTime: 0,
  lastActive: "",
  activityLevel: "medium",
  achievementCount: 0,
  gamePreferences: [],
  points: 0,
});

// 用户成就
const userAchievements = ref<EnhancedGameAchievement[]>([]);

// 游戏类型分布
const gameTypeDistribution = ref<GameTypeDistribution[]>([]);

// 每日游戏时长
const dailyPlayTime = ref<any[]>([]);

// 时段分布
const hourlyDistribution = ref<any[]>([]);

// 游戏进度列表
const gameProgressList = ref<any[]>([]);

// 选项
const timeRange = ref("30");
const sortOption = ref("lastPlayed");

// 计算平均评分
const formattedRating = computed(() => {
  return userInfo.averageRating ? userInfo.averageRating.toFixed(1) : "0.0";
});

// 监听排序和时间范围变化
const gameRecords = computed(() => {
  // 过滤和排序游戏记录
  let result = [...gameProgressList.value];

  // 应用时间范围筛选
  if (timeRange.value !== "all") {
    const daysAgo = parseInt(timeRange.value);
    const cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() - daysAgo);

    result = result.filter((game: any) => new Date(game.lastPlayed) >= cutoffDate);
  }

  // 应用排序
  if (sortOption.value === "playTime") {
    result.sort((a: any, b: any) => b.playTime - a.playTime);
  } else if (sortOption.value === "lastPlayed") {
    result.sort(
      (a: any, b: any) => new Date(b.lastPlayed).getTime() - new Date(a.lastPlayed).getTime()
    );
  } else if (sortOption.value === "name") {
    result.sort((a: any, b: any) => a.name.localeCompare(b.name));
  }

  return result;
});

// 查看特定游戏详情
const handleGameDetail = (game: any) => {
  ElMessage({
    message: `游戏: ${game.name}, 类型: ${getGameTypeName(game.gameType)}, 进度: ${game.progress}%`,
    type: "info",
  });
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 导出数据
const handleExport = () => {
  if (userId.value) {
    UserGameAPI.exportUserData({
      pageNum: 1,
      pageSize: 10,
      username: userInfo.username,
      activityLevel: "",
      startDate: "",
      endDate: "",
      sortField: "",
      sortOrder: "",
    })
      .then((res: any) => {
        // 直接处理响应，不检查code字段
        if (res) {
          ElMessage.success("数据导出成功");
          // 尝试不同的方式获取下载链接
          const fileUrl = res.data || res.fileUrl || res.url || res;
          if (fileUrl && typeof fileUrl === "string") {
            window.open(fileUrl, "_blank");
          }
        } else {
          ElMessage.error("数据导出失败");
        }
      })
      .catch((err) => {
        console.error("导出数据失败:", err);
        ElMessage.error("数据导出失败");
      });
  } else {
    ElMessage.warning("未获取到用户ID，无法导出数据");
  }
};

// 格式化总时间
const formatTotalTime = (seconds: number) => {
  if (!seconds) return "0小时";
  const hours = Math.floor(seconds / 3600);
  return `${hours}小时`;
};

// 格式化时间
const formatTime = (seconds: number) => {
  if (!seconds) return "0分钟";
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);

  if (hours > 0) {
    return `${hours}小时${minutes}分钟`;
  }
  return `${minutes}分钟`;
};

// 格式化日期
const formatDate = (date: Date | string): string => {
  if (!date) return "";
  const d = new Date(date);
  return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d.getDate().toString().padStart(2, "0")}`;
};

// 获取进度条颜色
const getProgressColor = (progress: number) => {
  if (progress < 30) return "#909399";
  if (progress < 70) return "#e6a23c";
  return "#67c23a";
};

// 获取游戏类型名称
const getGameTypeName = (type: string) => {
  const types: Record<string, string> = {
    shooting: "射击游戏",
    rpg: "角色扮演",
    strategy: "策略游戏",
    casual: "休闲游戏",
    default: "其他游戏",
  };

  return types[type] || types.default;
};

// 获取游戏类型标签类型
const getGameTypeTagType = (type: string) => {
  const types: Record<string, string> = {
    shooting: "danger",
    rpg: "primary",
    strategy: "warning",
    casual: "success",
    default: "info",
  };

  return types[type] || types.default;
};

// 加载用户统计数据
const loadUserStatistics = async () => {
  console.log("Loading statistics for user:", userId.value);
  loading.value = true;
  error.value = null;

  try {
    // 获取用户信息
    if (!userId.value) {
      ElMessage.warning("未获取到有效的用户ID");
      return;
    }

    // 获取用户信息
    const userInfoResponse: any = await UserGameAPI.getUserInfo(userId.value as number);
    console.log("User info response:", userInfoResponse);

    // 直接处理响应，不检查code字段
    if (userInfoResponse) {
      // 如果响应本身就是用户数据对象
      if (userInfoResponse.id && userInfoResponse.username) {
        Object.assign(userInfo, userInfoResponse);
      }
      // 如果响应有data字段
      else if (userInfoResponse.data) {
        Object.assign(userInfo, userInfoResponse.data);
      }
      console.log("User info loaded:", userInfo);
    } else {
      console.error("Failed to load user info:", userInfoResponse);
      ElMessage.error("加载用户信息失败");
    }

    // 获取用户成就
    const achievementsResponse: any = await UserGameAPI.getUserAchievements(userId.value as number);
    console.log("User achievements response:", achievementsResponse);

    // 直接处理响应，不检查code字段
    if (achievementsResponse) {
      // 如果响应是数组
      if (Array.isArray(achievementsResponse)) {
        userAchievements.value = achievementsResponse;
      }
      // 如果响应有data字段且是数组
      else if (achievementsResponse.data && Array.isArray(achievementsResponse.data)) {
        userAchievements.value = achievementsResponse.data;
      }
      console.log("User achievements loaded:", userAchievements.value);

      // 如果成就数组中的game属性不存在，添加默认值
      userAchievements.value.forEach((achievement: EnhancedGameAchievement) => {
        if (!achievement.game) {
          achievement.game = achievement.gameName || "未知游戏";
        }
        // 确保有默认图标
        if (!achievement.icon) {
          achievement.icon = "el-icon-trophy";
        }
        // 确保有解锁状态
        if (achievement.unlocked === undefined) {
          achievement.unlocked = !!achievement.unlockedDate;
        }
      });
    } else {
      console.log("No achievements data available");
    }

    // 获取游戏类型分布
    const typeDistributionResponse: any = await UserGameAPI.getGameTypeDistribution(
      userId.value as number
    );
    console.log("Game type distribution response:", typeDistributionResponse);

    // 直接处理响应，不检查code字段
    if (typeDistributionResponse) {
      // 如果响应是数组
      if (Array.isArray(typeDistributionResponse)) {
        gameTypeDistribution.value = typeDistributionResponse.map((item: any) => ({
          type: item.type || item.gameType,
          count: item.count || item.value || 1,
        }));
      }
      // 如果响应有data字段且是数组
      else if (typeDistributionResponse.data && Array.isArray(typeDistributionResponse.data)) {
        gameTypeDistribution.value = typeDistributionResponse.data.map((item: any) => ({
          type: item.type || item.gameType,
          count: item.count || item.value || 1,
        }));
      }
      console.log("Game type distribution loaded:", gameTypeDistribution.value);
    } else {
      console.log("No game type distribution data available");
    }

    // 获取每日游戏时长数据
    const dailyPlayTimeResponse: any = await UserGameAPI.getDailyPlayTime(userId.value as number);
    console.log("Daily play time response:", dailyPlayTimeResponse);

    // 直接处理响应，不检查code字段
    if (dailyPlayTimeResponse) {
      // 如果响应是数组
      if (Array.isArray(dailyPlayTimeResponse)) {
        dailyPlayTime.value = dailyPlayTimeResponse.map((item: any) => ({
          date: item.date || formatDate(item.day),
          playTime: item.playTime || item.time || 0,
        }));
      }
      // 如果响应有data字段且是数组
      else if (dailyPlayTimeResponse.data && Array.isArray(dailyPlayTimeResponse.data)) {
        dailyPlayTime.value = dailyPlayTimeResponse.data.map((item: any) => ({
          date: item.date || formatDate(item.day),
          playTime: item.playTime || item.time || 0,
        }));
      }
      console.log("Daily game time data loaded:", dailyPlayTime.value);
    } else {
      console.log("No daily game time data available");
      // 如果没有数据，使用模拟数据以便图表仍然可以显示
      dailyPlayTime.value = generateMockDailyPlayTime();
    }

    // 获取时段分布数据
    const hourlyResponse: any = await UserGameAPI.getHourlyDistribution(userId.value as number);
    console.log("Hourly distribution response:", hourlyResponse);

    // 直接处理响应，不检查code字段
    if (hourlyResponse) {
      // 如果响应是数组
      if (Array.isArray(hourlyResponse)) {
        hourlyDistribution.value = hourlyResponse.map((item: any) => ({
          hour: item.hour !== undefined ? item.hour : parseInt(item.timeSlot || "0"),
          playTime: item.playTime || item.time || 0,
        }));
      }
      // 如果响应有data字段且是数组
      else if (hourlyResponse.data && Array.isArray(hourlyResponse.data)) {
        hourlyDistribution.value = hourlyResponse.data.map((item: any) => ({
          hour: item.hour !== undefined ? item.hour : parseInt(item.timeSlot || "0"),
          playTime: item.playTime || item.time || 0,
        }));
      }
      console.log("Hourly distribution data loaded:", hourlyDistribution.value);
    } else {
      console.log("No hourly distribution data available");
      // 如果没有数据，使用模拟数据
      hourlyDistribution.value = generateMockHourlyDistribution();
    }

    // 加载游戏进度列表
    const gameProgressResponse: any = await UserGameAPI.getGameProgressList(
      userId.value as number,
      10
    );
    console.log("Game progress response:", gameProgressResponse);

    // 直接处理响应，不检查code字段
    if (gameProgressResponse) {
      // 如果响应是数组
      if (Array.isArray(gameProgressResponse)) {
        gameProgressList.value = gameProgressResponse.map((item: Record<string, any>) => ({
          id: item.id,
          name: item.name || item.gameName || "未命名游戏",
          gameType: item.gameType || "default",
          playTime: item.playTime || 0,
          startDate: item.startDate || item.createTime,
          lastPlayed: item.lastPlayed || item.updateTime || new Date().toISOString(),
          progress: item.progress || 0,
          rating: item.rating || 0,
        }));
      }
      // 如果响应有data字段且是数组
      else if (gameProgressResponse.data && Array.isArray(gameProgressResponse.data)) {
        gameProgressList.value = gameProgressResponse.data.map((item: Record<string, any>) => ({
          id: item.id,
          name: item.name || item.gameName || "未命名游戏",
          gameType: item.gameType || "default",
          playTime: item.playTime || 0,
          startDate: item.startDate || item.createTime,
          lastPlayed: item.lastPlayed || item.updateTime || new Date().toISOString(),
          progress: item.progress || 0,
          rating: item.rating || 0,
        }));
      }
      console.log("Game progress data loaded:", gameProgressList.value);
    } else {
      console.log("No game progress data available");
    }

    // 确保DOM已渲染后初始化图表
    nextTick(() => {
      initCharts();
    });
  } catch (e) {
    console.error("Error loading user statistics:", e);
    error.value = e;
    ElMessage.error("加载统计数据失败");
  } finally {
    loading.value = false;
  }
};

// 生成模拟的每日游戏时长数据（当API返回为空时使用）
const generateMockDailyPlayTime = () => {
  const mockData = [];
  const now = new Date();
  for (let i = 30; i >= 0; i--) {
    const date = new Date();
    date.setDate(now.getDate() - i);
    const formattedDate = formatDate(date);
    // 随机游戏时长 (0-5小时，转换为秒)
    const playTime = Math.floor(Math.random() * 5 * 3600);
    mockData.push({
      date: formattedDate,
      playTime: playTime,
    });
  }
  return mockData;
};

// 生成模拟的时段分布数据（当API返回为空时使用）
const generateMockHourlyDistribution = () => {
  const mockData = [];
  for (let hour = 0; hour < 24; hour++) {
    // 白天时段游戏时间更长
    let playTime = 0;
    if (hour >= 9 && hour <= 23) {
      // 晚上高峰期 18-23点
      if (hour >= 18 && hour <= 23) {
        playTime = Math.floor(Math.random() * 5000) + 3000;
      } else {
        playTime = Math.floor(Math.random() * 2000) + 1000;
      }
    } else {
      // 深夜/凌晨时段较少
      playTime = Math.floor(Math.random() * 500);
    }
    mockData.push({
      hour: hour,
      playTime: playTime,
    });
  }
  return mockData;
};

// 初始化图表
const initCharts = () => {
  console.log("初始化图表开始", {
    timeChartRef: timeChartRef.value,
    typeChartRef: typeChartRef.value,
    hourlyChartRef: hourlyChartRef.value,
    progressChartRef: progressChartRef.value,
  });

  // 使用setTimeout确保DOM已完全渲染
  setTimeout(() => {
    try {
      if (timeChartRef.value && dailyPlayTime.value && dailyPlayTime.value.length > 0) {
        console.log("初始化时间图表...");
        initTimeChart();
      } else {
        console.warn("时间图表初始化条件不满足:", {
          ref: !!timeChartRef.value,
          data: !!dailyPlayTime.value,
          length: dailyPlayTime.value?.length,
        });
      }

      if (
        typeChartRef.value &&
        gameTypeDistribution.value &&
        gameTypeDistribution.value.length > 0
      ) {
        console.log("初始化类型图表...");
        initTypeChart();
      } else {
        console.warn("类型图表初始化条件不满足:", {
          ref: !!typeChartRef.value,
          data: !!gameTypeDistribution.value,
          length: gameTypeDistribution.value?.length,
        });
      }

      if (hourlyChartRef.value && hourlyDistribution.value && hourlyDistribution.value.length > 0) {
        console.log("初始化时段图表...");
        initHourlyChart();
      } else {
        console.warn("时段图表初始化条件不满足:", {
          ref: !!hourlyChartRef.value,
          data: !!hourlyDistribution.value,
          length: hourlyDistribution.value?.length,
        });
      }

      if (progressChartRef.value && gameProgressList.value && gameProgressList.value.length > 0) {
        console.log("初始化进度图表...");
        initProgressChart();
      } else {
        console.warn("进度图表初始化条件不满足:", {
          ref: !!progressChartRef.value,
          data: !!gameProgressList.value,
          length: gameProgressList.value?.length,
        });
      }
    } catch (err) {
      console.error("图表初始化过程中发生错误:", err);
    }
  }, 500);
};

// 初始化时间趋势图表
const initTimeChart = () => {
  try {
    // 检查DOM元素是否存在
    if (!timeChartRef.value) {
      console.warn("时间图表容器不存在");
      return;
    }

    // 如果已存在图表实例，先销毁
    if (timeChart) {
      timeChart.dispose();
      timeChart = null;
    }

    // 创建新的图表实例
    timeChart = echarts.init(timeChartRef.value);

    // 准备数据
    const dates = dailyPlayTime.value.map((item) => item.date || formatDate(item.day));
    const times = dailyPlayTime.value.map((item) => item.playTime || item.time || 0);

    const option = {
      title: {
        text: "每日游戏时长趋势",
        left: "center",
      },
      tooltip: {
        trigger: "axis",
        formatter: function (params: any[]) {
          const data = params[0].data;
          return `${params[0].axisValue}<br/>${formatTime(data)}`;
        },
      },
      xAxis: {
        type: "category",
        data: dates,
        axisLabel: {
          rotate: 45,
        },
      },
      yAxis: {
        type: "value",
        axisLabel: {
          formatter: function (value: number) {
            return formatTime(value);
          },
        },
      },
      series: [
        {
          data: times,
          type: "line",
          smooth: true,
          areaStyle: {
            opacity: 0.3,
          },
          lineStyle: {
            width: 3,
          },
          itemStyle: {
            color: "#409EFF",
          },
        },
      ],
    };

    // 设置配置项
    timeChart.setOption(option);
    console.log("时间图表初始化成功");
  } catch (error) {
    console.error("初始化每日游戏时长图表失败:", error);
  }
};

// 初始化游戏类型分布图表
const initTypeChart = () => {
  try {
    // 检查DOM元素是否存在
    if (!typeChartRef.value) {
      console.warn("类型图表容器不存在");
      return;
    }

    // 如果已存在图表实例，先销毁
    if (typeChart) {
      typeChart.dispose();
      typeChart = null;
    }

    // 创建新的图表实例
    typeChart = echarts.init(typeChartRef.value);

    // 准备数据
    const data = gameTypeDistribution.value.map((item) => ({
      name: getGameTypeName(item.type),
      value: item.count,
    }));

    const option = {
      title: {
        text: "游戏类型分布",
        left: "center",
      },
      tooltip: {
        trigger: "item",
        formatter: "{b}: {c} ({d}%)",
      },
      legend: {
        orient: "vertical",
        left: "left",
        data: data.map((item) => item.name),
      },
      series: [
        {
          type: "pie",
          radius: "65%",
          center: ["50%", "50%"],
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
          label: {
            formatter: "{b}: {d}%",
          },
        },
      ],
    };

    // 设置配置项
    typeChart.setOption(option);
    console.log("类型图表初始化成功");
  } catch (error) {
    console.error("初始化游戏类型分布图表失败:", error);
  }
};

// 初始化时段分布图表
const initHourlyChart = () => {
  try {
    // 检查DOM元素是否存在
    if (!hourlyChartRef.value) {
      console.warn("时段图表容器不存在");
      return;
    }

    // 如果已存在图表实例，先销毁
    if (hourlyChart) {
      hourlyChart.dispose();
      hourlyChart = null;
    }

    // 创建新的图表实例
    hourlyChart = echarts.init(hourlyChartRef.value);

    // 准备数据
    const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`);
    const data = Array(24).fill(0);

    // 填充数据
    hourlyDistribution.value.forEach((item) => {
      const hour = typeof item.hour === "number" ? item.hour : parseInt(String(item.hour || 0));
      if (hour >= 0 && hour < 24) {
        data[hour] = item.playTime || 0;
      }
    });

    const option = {
      title: {
        text: "游戏时段分布",
        left: "center",
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        formatter: function (params: any[]) {
          return `${params[0].axisValue}<br/>游戏时长: ${formatTime(params[0].data)}`;
        },
      },
      xAxis: {
        type: "category",
        data: hours,
        axisLabel: {
          interval: 2,
          rotate: 45,
        },
      },
      yAxis: {
        type: "value",
        axisLabel: {
          formatter: function (value: number) {
            return formatTime(value);
          },
        },
      },
      series: [
        {
          data: data,
          type: "bar",
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#83bff6" },
              { offset: 0.5, color: "#188df0" },
              { offset: 1, color: "#188df0" },
            ]),
          },
        },
      ],
    };

    // 设置配置项
    hourlyChart.setOption(option);
    console.log("时段图表初始化成功");
  } catch (error) {
    console.error("初始化时段分布图表失败:", error);
  }
};

// 初始化游戏进度图表
const initProgressChart = () => {
  try {
    // 检查DOM元素是否存在
    if (!progressChartRef.value) {
      console.warn("进度图表容器不存在");
      return;
    }

    // 如果已存在图表实例，先销毁
    if (progressChart) {
      progressChart.dispose();
      progressChart = null;
    }

    // 创建新的图表实例
    progressChart = echarts.init(progressChartRef.value);

    // 准备数据 - 只显示前5个游戏，避免图表过长
    const topGames = [...gameProgressList.value]
      .sort((a, b) => b.progress - a.progress)
      .slice(0, 5);

    const games = topGames.map((item) => item.name || item.gameName);
    const progress = topGames.map((item) => item.progress || 0);

    const option = {
      title: {
        text: "游戏完成进度",
        left: "center",
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        formatter: "{b}: {c}%",
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: {
        type: "value",
        max: 100,
        axisLabel: {
          formatter: "{value}%",
        },
      },
      yAxis: {
        type: "category",
        data: games,
      },
      series: [
        {
          name: "进度",
          type: "bar",
          data: progress,
          label: {
            show: true,
            position: "right",
            formatter: "{c}%",
          },
          itemStyle: {
            color: function (params: { data: number }) {
              const progress = params.data;
              if (progress < 30) return "#909399";
              if (progress < 70) return "#e6a23c";
              return "#67c23a";
            },
          },
        },
      ],
    };

    // 设置配置项
    progressChart.setOption(option);
    console.log("进度图表初始化成功");
  } catch (error) {
    console.error("初始化游戏进度图表失败:", error);
  }
};

// 监听窗口大小变化，调整图表
window.addEventListener("resize", () => {
  timeChart?.resize();
  typeChart?.resize();
  hourlyChart?.resize();
  progressChart?.resize();
});

// 组件挂载时加载数据
onMounted(() => {
  console.log("统计页面挂载，路由参数:", route.query);

  // 延迟一点时间确保DOM完全渲染
  setTimeout(() => {
    if (userId.value) {
      console.log("开始加载用户统计数据，用户ID:", userId.value);
      loadUserStatistics();
    } else {
      console.warn("未获取到有效的用户ID，请从用户列表点击进入");
      ElMessage.warning("未获取到用户ID，请从用户列表点击进入");
      setTimeout(() => {
        router.push("/userinfo/list");
      }, 2000);
    }
  }, 100);
});

// 组件卸载时销毁图表实例
onUnmounted(() => {
  if (timeChart) {
    timeChart.dispose();
    timeChart = null;
  }
  if (typeChart) {
    typeChart.dispose();
    typeChart = null;
  }
  if (hourlyChart) {
    hourlyChart.dispose();
    hourlyChart = null;
  }
  if (progressChart) {
    progressChart.dispose();
    progressChart = null;
  }
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.page-title {
  margin: 0 0 0 15px;
  font-size: 20px;
}

.statistics-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.stat-card {
  height: 120px;
}

.stat-card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #f56c6c;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  margin-right: 15px;
}

.stat-icon.blue {
  background-color: #409eff;
}

.stat-icon.green {
  background-color: #67c23a;
}

.stat-icon.purple {
  background-color: #9b59b6;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-row {
  margin-bottom: 0;
}

.chart-card {
  height: 380px;
  overflow: hidden;
}

.chart-header {
  display: flex;
  align-items: center;
}

.chart-header i {
  margin-left: 8px;
  color: #909399;
  cursor: pointer;
}

.chart-placeholder {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
  border-radius: 4px;
  position: relative;
  overflow: hidden;
  min-height: 300px;
  width: 100%;
}

.chart-placeholder::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  transform: translateX(-100%);
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  100% {
    transform: translateX(100%);
  }
}

.detail-header,
.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.achievement-card {
  margin-bottom: 0;
}

.achievement-content {
  display: flex;
  align-items: center;
}

.achievement-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  margin-right: 15px;
  transition: transform 0.3s ease;
}

.achievement-info {
  flex: 1;
}

.achievement-info h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.achievement-info p {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #606266;
}

.achievement-game {
  font-size: 12px;
  color: #909399;
}

.achievement-card:hover .achievement-icon {
  transform: scale(1.1);
}

.achievement-card {
  transition: box-shadow 0.3s ease;
  cursor: pointer;
}

.achievement-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
